//
//  YearSelectViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/30.
//

import UIKit
typealias YearSelectViewControllerBlock = (String)->Void
class YearSelectViewController: BaseViewController {
    var callBack: YearSelectViewControllerBlock?
    var bgDissBtn: UIButton!
    var bgView: UIView!
    var contentH: CGFloat = 360
    var collectionView: UICollectionView!
    var yearLab: UILabel!
    var index = 9999
    var dataArray: [String] = []
    var tenArray: [String] = []
    var page = 1
    var rightBtn: UIButton!
    var leftBtn: UIButton!
    var curYear: String = "" //当前选中的year传进来的
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.isHidden = true
        self.view.backgroundColor = .clear
        self.dataArray = XTManageCenter.getCarCreateDate()
        if self.curYear != "", let pIndex = self.dataArray.firstIndex(where: {$0 == self.curYear}) {
            //说明有传值进来的
            self.page = pIndex/10 + 1
        }else{
            self.page = self.dataArray.count/10
        }
        
        self.tenArray = self.getDataByPage(page: self.page)
        self.index = self.tenArray.firstIndex(where: {$0 == curYear}) ?? 9999
        self.initSubiew()
    }
    
    ///从后往前取
    ///page 的前一页
    ///第13页 = array[page-1 * 10]
    private func getDataByPage(page: NSInteger) -> [String] {
        let start =  (self.page - 1) * 10
        guard self.dataArray.count > start else {
            return []
        }
        let tempArr = Array(self.dataArray[start...(start + 9)])
        return tempArr.reversed()
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startAnimationAction()
    }
    
    
    func initSubiew() {
        self.bgDissBtn = UIButton.init(type: UIButtonType.custom)
        self.bgDissBtn.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        self.bgDissBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0)
        self.bgDissBtn.addTarget(self, action: #selector(hiddenActionView), for: .touchUpInside)
        self.view.addSubview(self.bgDissBtn)
        
        self.bgView = UIView(frame: CGRect(x: 0, y: kScreenWidth, width: kScreenWidth, height: kScreenHeight))
        self.bgView.backgroundColor = .white
        self.bgDissBtn.addSubview(self.bgView)
        bgView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 10)
        
        let tempHeaderView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth, height: contentH))
        //做圆角背景
        tempHeaderView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 100)
        tempHeaderView.backgroundColor = .white
        tempHeaderView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 10)
        self.bgView.addSubview(tempHeaderView)
        
        let tempTitleLab = UILabel.init(frame: CGRect.init(x: kScreenWidth/2 - 160, y: 0, width: 320, height: 56))
        tempTitleLab.backgroundColor = UIColor.clear
        tempTitleLab.textAlignment = .center
        tempTitleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        tempTitleLab.textColor = Theme.titleLabColor
        tempTitleLab.numberOfLines = 0
        tempTitleLab.text = MMLocalizedString("year_manufacture", comment: "制造年份")
        tempHeaderView.addSubview(tempTitleLab)
        
        leftBtn = UIButton(frame: CGRect(x: 0, y: tempTitleLab.frame.maxY + 10, width: 30, height: 30))
        leftBtn.setup_image(image: UIImage.init(named: "calendar_left"))
        leftBtn.addTarget(self, action: #selector(leftBtnAntion), for: .touchUpInside)
        tempHeaderView.addSubview(leftBtn)
        
        
        self.yearLab = UILabel(frame: CGRect(x: 0, y: tempTitleLab.frame.maxY + 10, width: kScreenWidth, height: 30))
        self.yearLab.textColor = Theme.titleLabColor
        self.yearLab.font = UIFont(name: Theme.PingFangSCRegular, size: 14)
        self.yearLab.textAlignment = .center
        self.getBarTitle()
        tempHeaderView.addSubview( self.yearLab)
        
        
        rightBtn = UIButton(frame: CGRect(x: kScreenWidth - 30, y: tempTitleLab.frame.maxY + 10, width: 30, height: 30))
        rightBtn.setup_image(image: UIImage.init(named: "calendar_right"))
        rightBtn.addTarget(self, action: #selector(rightBtnAntion), for: .touchUpInside)
        tempHeaderView.addSubview(rightBtn)
        

        let layout = MHCollectionViewFlowlayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 12
        let ww = (kScreenWidth - 28 - 3*10)/4
        layout.itemSize = CGSize(width: ww, height: 38)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14)
        self.collectionView = UICollectionView(frame: CGRect(x: 0, y: rightBtn.frame.maxY + 20, width: kScreenWidth, height: 100), collectionViewLayout: layout)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = .white
        self.collectionView.register(YearCollectionViewCell.self, forCellWithReuseIdentifier: "YearCollectionViewCell")
        self.bgView.addSubview(self.collectionView)
        
        self.collectionView.snp.makeConstraints { make in
            make.top.equalTo(rightBtn.snp.bottom).offset(20)
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.height.equalTo(100)
            make.bottom.equalTo(-10)
        }
    }
 
    ///页面展示动画
    @objc func startAnimationAction(){
        self.view.handleLoading()
        self.bgView.frame.origin.y = kScreenHeight
        self.bgDissBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0 )
        let orginY = kScreenHeight - self.contentH
        UIView.animate(withDuration: 0.2, animations: {
            self.bgDissBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.6)
            self.bgView.frame.origin.y = orginY
        }) { (flag) in
            //
        }
    }
    
    /// 隐藏,没有点添加到购物车按钮
    @objc func hiddenActionView(){
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.24, delay: 0, options: opts, animations: {
            self.bgDissBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
            self.bgView.frame.origin.y = kScreenHeight
        }, completion: { _ in
            //self.callBack?()
            self.dismiss(animated: false) {
            }
        })
    }
    
    ///获取标题
    private func getBarTitle(){
        if self.tenArray.count > 0{
            let endStr = self.tenArray.first
            let start = self.tenArray.last(where: {$0 != ""})
            self.yearLab.text = String(format: "%@-%@%@", start!,endStr!,MMLocalizedString("year", comment: "年"))
        }
    }
    
    //减
    @objc func leftBtnAntion(){
        if self.page <= 1 {
            return
        }
        self.page = self.page - 1
        self.tenArray = self.getDataByPage(page: self.page)
        self.getBarTitle()
        self.collectionView.reloadData()
    }
    
    //加
    @objc func rightBtnAntion(){
        if self.page >= self.dataArray.count/10 {
            return
        }
        self.tenArray = []
        self.page = self.page + 1
        self.tenArray = self.getDataByPage(page: self.page)
        self.getBarTitle()
        self.collectionView.reloadData()
    }

}


extension YearSelectViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.tenArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YearCollectionViewCell", for: indexPath) as! YearCollectionViewCell

        cell.titleLab.text = (self.tenArray[indexPath.row])
        if indexPath.row == self.index{
            cell.bgView.backgroundColor = UIColor(hex: 0xFFCC32,alpha: 0.15)
            cell.bgView.layer.borderWidth = 1
            cell.bgView.layer.borderColor = UIColor(hex: 0xFFCC32).cgColor
            cell.titleLab.font = UIFont(name: Theme.PingFangSCMedium, size: 14)
        }else{
            cell.bgView.backgroundColor = UIColor(hex: 0xF7F8FB)
            cell.bgView.layer.borderWidth = 0
            cell.bgView.layer.borderColor = UIColor.clear.cgColor
            cell.titleLab.font = UIFont(name: Theme.PingFangSCRegular, size: 14)
        }
        if cell.titleLab.text == "" {
            cell.isHidden = true
        }else{
            cell.isHidden = false
        }
      
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.tenArray.count > indexPath.row {
            self.index = indexPath.row
            self.collectionView.reloadData()
            self.perform(#selector(self.handleSelect), afterDelay: 0.5)
        }
    }
    
    @objc func handleSelect(){
        self.callBack?(self.tenArray[self.index])
        self.hiddenActionView()
    }
}

class YearCollectionViewCell: UICollectionViewCell {
    var bgView: UIView!
    var titleLab: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        self.clipsToBounds = true
        
        self.bgView = UIView(frame: .zero)
        self.bgView.backgroundColor = UIColor(hex: 0xF7F8FB)
        self.bgView.layer.cornerRadius = 4
        self.bgView.clipsToBounds = true
        self.contentView.addSubview(self.bgView)
        
  
        
        self.titleLab = UILabel(frame: .zero)
        self.titleLab.font = UIFont(name: Theme.PingFangSCRegular, size: 14)
        self.titleLab.textColor = Theme.titleLabColor
        self.titleLab.textAlignment = .center
        self.bgView.addSubview(self.titleLab)
        
        
        self.bgView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(38)
        }
        
     
        self.titleLab.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(38)
        }
        
        
    }
    
   
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
